﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Arduino.ControlPanel
{
    public partial class frmControlPanel : Form
    {
        private Firmata.Firmata mFirmata = null;
        public frmControlPanel(Firmata.Firmata _firmata)
        {
            InitializeComponent();
            mFirmata = _firmata;
            RefreshPanel();
        }

        private IUcPin FindPinControl(Firmata.Types.Pins pin)
        {
            try
            {
                foreach (Control control in this.Controls)
                {
                    if (control.GetType().GetInterface(typeof(IUcPin).FullName) != null)
                    {
                        IUcPin interf = (IUcPin)control;
                        if (interf.GetPin() == pin) return interf;
                    }
                }
            }
            catch (Exception)
            {
            }
            return null;
        }

        public void RefreshPanel()
        {
            if (this.InvokeRequired)
            {

            }
            if (mFirmata != null)
            {
                var pinlist = mFirmata.getPinList();
                var pinrepmodelist = mFirmata.getPinsReportMode();
                List<Control> list = new List<Control>();
                bool added = false;
                foreach (var pin in pinlist)
                {
                    IUcPin control = FindPinControl(pin);
                    if (control == null)
                    {
                        if (Firmata.Types.Types.IsPinDigital(pin)) control = (IUcPin)new ucPinDigital(pin, mFirmata);
                        else if (Firmata.Types.Types.IsPinAnalog(pin)) control = (IUcPin)new ucPinAnalog(pin, mFirmata);

                        if (control != null)
                        {
                            Control contr = (Control)control;
                            contr.Dock = DockStyle.Top;
                            contr.BringToFront();
                            this.Controls.Add(contr);
                            added = true;
                        }
                    }

                    if (control != null)
                    {
                        control.RefreshPin();
                        list.Add((Control)control);
                    }
                }

                if (added)
                    for (int i = 0; i < list.Count; i++)
                        list[i].BringToFront();
            }
        }
    }
}
